package com.du.cloud.service.oauth.endpoint;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import com.du.cloud.common.base.constant.RedisKeyConstants;
import com.du.cloud.common.base.exception.ValidateCodeException;
import com.du.cloud.common.base.model.dto.VerifyCodeDto;
import com.du.cloud.common.base.utils.Result;
import com.du.cloud.common.base.utils.UidUtil;
import com.du.cloud.common.cache.utils.RedisUtil;
import com.google.code.kaptcha.Producer;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * Desc:
 * Author: dushuang
 * Date: 2020/6/4
 **/
@Slf4j
@RestController
public class VerifyEndpoint {

    @Resource
    private Producer producer;
    @Value("${spring.profiles.active:dev}")
    private String env;

    @PostMapping(value = "captcha/generate")
    public Result captchaGenerate (String imgToken) {
        if (StrUtil.isEmpty(imgToken)) {
            // 新生成验证码
            imgToken = UidUtil.getRandomUid();
        }
        try {
            VerifyCodeDto codeDto = new VerifyCodeDto();
            codeDto.setImgToken(imgToken);
            byte[] imgData = createCodeImage(codeDto);
            // 图片base64处理
            String base64Img = Base64.encode(imgData);
            codeDto.setImg(base64Img);
            return Result.ok(codeDto);
        } catch (IOException e) {
            log.error("ImageIO write err", e);
            return Result.fail(e.getMessage());
        }
    }

    private byte[] createCodeImage(VerifyCodeDto codeDto) throws IOException {
        //生成验证码
        String text = producer.createText();
        BufferedImage image = producer.createImage(text);

        if (StrUtil.equals(env, "dev")) {
            codeDto.setCode(text);
        }
        //保存验证码信息
        if (RedisUtil.set(RedisKeyConstants.CAPTCHA_CODE.concat(codeDto.getImgToken()), text, 60L)) {
            // 转换流信息写出
            FastByteArrayOutputStream os = new FastByteArrayOutputStream();
            ImageIO.write(image, "jpeg", os);
            log.info("生成验证码 {} 成功!", text);
            return os.toByteArray();
        }

        throw new ValidateCodeException("生成验证码异常!");

    }
}
